package cn.hesion.leetcode;


import java.text.CharacterIterator;

class TextEditor {
    BInode dummyHead;
    BInode cursor;

    public TextEditor() {
        dummyHead = new BInode();
        cursor = dummyHead;
    }

    public void addText(String text) {
        char[] s = text.toCharArray();
        BInode cusorNext = cursor.next;
        BInode now = this.cursor;
        for (int i = 0; i < s.length; i++) {
            BInode newNode = new BInode(s[i]);
            now.next = newNode;
            now.next.prev = now;
            now = now.next;
        }
        now.next = cusorNext;
        if (cusorNext != null) {
            cusorNext.prev = now;
        }
        cursor = now;
    }

    public int deleteText(int k) {
        int cnt = 0;

        while (cursor != dummyHead && k-- > 0) {
            ++cnt;
            cursor.prev.next = cursor.next;
            if ( cursor.next != null) {
                cursor.next.prev= cursor.prev;
            }
            cursor = cursor.prev;
        }
        return cnt;
    }

    public String cursorLeft(int k) {
        //leetpractice
        while (cursor != dummyHead && k-- > 0) {
            cursor = cursor.prev;
        }
        return getMinLeftString(10);
    }

    private String getMinLeftString(int n) {
        StringBuilder sb = new StringBuilder();
        BInode now = this.cursor;
        while (now != dummyHead && n-- > 0) {
            sb.append(now.c);
            now = now.prev;
        }
        return sb.reverse().toString();
    }

    public String cursorRight(int k) {
        while (cursor.next != null && k-- > 0) {
            cursor = cursor.next;
        }
        return getMinLeftString(10);
    }

    public void printLink() {
        System.out.println("==========S===========");
        BInode now = this.dummyHead.next;
        while (now != null) {
            if (now.next == null) {
                System.out.print(now.c);
            } else {
                System.out.print(now.c + "->");
            }
            now = now.next;
        }
        System.out.println();
        System.out.println("==========E===========");
    }

    public static void main(String[] args) {
        TextEditor obj = new TextEditor();
        obj.addText("leetcode");
        obj.printLink();
        int param_2 = obj.deleteText(4);
        obj.printLink();
        obj.addText("practice");
        obj.printLink();
        String param_3 = obj.cursorRight(3);
        String param_4 = obj.cursorLeft(8);
        int param_5 = obj.deleteText(10);
        String param_6 = obj.cursorLeft(2);
        String param_7 = obj.cursorRight(6);
    }


}

class BInode {
    Character c;
    BInode prev, next;

    public BInode() {
    }

    public BInode(Character c) {
        this.c = c;
    }
}